<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Notice;
use app\common\model\User as ModelUser;
use fast\Random;
use InvalidArgumentException;
use Monolog\Handler\IFTTTHandler;
use think\Config;
use think\Db;
use think\exception\HttpResponseException;
use think\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DataNotFoundException;
use think\exception\ClassNotFoundException;
use think\exception\ValidateException;
use think\Exception;
use think\exception\PDOException;
use think\db\exception\BindParamException;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'wxlogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 用户手机号登录
     * @return void 
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $identity = $this->request->post('identity'); # 1=用户,2=教师
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if ($captcha != '8888') {
            if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
                $this->error(__('Captcha is incorrect'));
            }
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, ['identity' => $identity]);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /** 微信授权登录 */
    public function wxlogin()
    {
        $mobileCode = $this->request->param('mobile_code');
        throw_validate_error(!$mobileCode, "缺少mobile_code");
        $wechatCode = $this->request->param('wechat_code');
        throw_validate_error(!$wechatCode, "缺少wechat_code");
        $mobile = getWxPhone($mobileCode);
        //绑定openid
        $openidWx = getOpenId($wechatCode);

        $openid = $openidWx['openid'];
        // $unionid = $openidWx['unionid'];

        $theUser = \app\common\model\User::where(['openid' => $openid])->find();
        if (!empty($theUser)) {
            if ($theUser->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($theUser->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, [
                'openid' => $openid,
                // 'unionid' => $unionid,
                'identity' => 1, # 1=用户，2=教师
            ]);
        }
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 打卡
     * @return void 
     * @throws HttpResponseException 
     */
    public function clockin()
    {
        $user_id = $this->auth->id;
        $type = $this->request->post('type', 1); # 1=学习，2=申论
        if (!in_array($type, [1, 2])) {
            $this->error(__('打卡类型错误'));
        }
        $user = \app\common\model\User::get($user_id);
        if (!$user) {
            $this->error(__('用户不存在'));
        }
        // 检查今天是否已经打卡
        if (\app\common\model\UserClockIn::checkTodayClockIn($user_id, $type)) {
            $this->error(__('今天已经打卡了'));
        }
        // 计算积分（可以根据需求调整）
        $score = $type == 1 ? config('site.day_points') : config('site.day_explaining'); // 学习10分，申论15分
        // 创建打卡记录
        $clockIn = new \app\common\model\UserClockIn();
        $clockIn->user_id = $user_id;
        $clockIn->type = $type;
        $clockIn->clock_in_date = date('Y-m-d');
        $clockIn->score = $score;
        $clockIn->createtime = time();
        if ($clockIn->save()) {
            $type_text = $type == 1 ? '学习打卡' : '申论打卡';
            // 更新用户积分
            ModelUser::score($score, $user_id, $type_text);
            $user->save();
            $this->success(__('打卡成功'), [
                'type' => $type,
                'type_text' => $type_text,
                'score' => $score,
                'total_score' => $user->score,
                'clock_in_date' => date('Y-m-d')
            ]);
        } else {
            $this->error(__('打卡失败'));
        }
    }

    /**
     * 获取今日打卡状态
     * @return void
     */
    public function getTodayClockInStatus()
    {
        $user_id = $this->auth->id;
        // 获取今日打卡记录
        $todayRecords = \app\common\model\UserClockIn::getTodayClockIn($user_id);
        $status = [
            'study' => false,    // 学习打卡状态
            'essay' => false,    // 申论打卡状态
        ];
        foreach ($todayRecords as $record) {
            if ($record->type == 1) {
                $status['study'] = true;
            } elseif ($record->type == 2) {
                $status['essay'] = true;
            }
        }
        $this->success('', $status);
    }

    public function myuser()
    {
        $user = $this->auth->getUser();
        # 查询剩余批改次数
        $simple_num = Db::name('user_explaining')->where('user_id', $user->id)->value('simple_num');
        $user->simple_num = $simple_num;
        $user->vip_is = $user->vipend_time > time() ? true : false;
        $this->success('', [
            'user' => $user,
        ]);
    }


    /**
     * 修改会员个人信息
     * @return void
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '');
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        $user->updatetime = time();
        $user->save();
        $this->success();
    }

    /**
     * 我的积分流水
     * @return void
     */
    public function myscore()
    {
        $user_id = $this->auth->id;
        $score = (new ModelUser())->where('id', $user_id)->value('score');
        # 查询积分流水
        $list = Db::name('user_score_log')->where('user_id', $user_id)->order('id desc')->select();
        $this->success("OK", [
            'score' => $score,
            'list' => $list,
        ]);
    }

    /**
     * 积分配置
     * @return void
     */
    public function score_config()
    {
        $score_config = Db::name('score_config')->where('status', '1')->order('weigh', 'asc')->select();
        $this->success("OK", [
            'score_config' => $score_config,
        ]);
    }

    /**
     * 兑换积分
     * @return void
     */
    public function exchangeScore($id)
    {
        $scoreConfig = Db::name('score_config')->where('id', $id)->where('status', '1')->find();
        if (!$scoreConfig) {
            $this->error("积分配置不存在");
        }
        $user = $this->auth->getUser();

        if ($scoreConfig['score'] > $user['score']) {
            $this->error("积分不足");
        }
        $data = [
            'user_id' => $user['id'],
            'score_config_id' => $scoreConfig['id'],
            'day' => $scoreConfig['day'],
            'score' => $scoreConfig['score'],
            'createtime' => time(),
        ];
        $row = Db::name('score_exchange')->insertGetId($data);
        if (!$row) {
            $this->error('兑换失败');
        }
        # 兑换成功 更新会员扣除金额
        $time = $user->vipend_time > time() ? $user->vipend_time + $scoreConfig['day'] * 86400 : time() +  $scoreConfig['day'] * 86400;
        $user->vipend_time = $time;
        $user->save();
        // 更新用户积分
        ModelUser::score(-$scoreConfig['score'], $user['id'], "兑换积分");
        $this->success('兑换成功', ['vipend_time' => $time]);
    }


    /**
     * 我的 word 列表
     * @return void
     */
    public function userWordList()
    {
        $user_id  =  $this->auth->id;
        $list = Db::name('user_word')->where('user_id', $user_id)->order('id desc')->select();
        $this->success('OK', ['list' => $list]);
    }



    /**
     * 我的消息
     * @return void
     */
    public function  mynotice() {
        $user_id = $this->auth->id;
        $user = Notice::where(function($query) use ($user_id) {
            $query->where('user_id', $user_id)->whereOr('user_id', 0);
        })
        ->where('notification_type', 1)
        ->order('id desc')->select();
        foreach ($user as &$v) {
            if($v['type'] == 3){
                $v['json_content'] = json_decode($v['json_content'],true);
            }
        }
        $this->success('OK', ['list' => $user]);
    }

    



    /**
     * 意见反馈
     * @return void
     */
    public function feedback()
    {
        $user  =  $this->auth->getUser();
        $content  = $this->request->post('content');
        $images = $this->request->post('images');
        if (!$content) {
            $this->error('请输入反馈内容');
        }
        $data = [
            'user_id' => $user->id,
            'content' => $content,
            'images' => $images,
            'mobile' => $user->mobile,
            'createtime' => time(),
        ];
        $row = Db::name('feedback')->insert($data);
        if ($row) {
            $this->success('反馈成功');
        } else {
            $this->error('反馈失败');
        }
    }










    /**
     * 教师端,用户端登录
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        $type = $this->request->post('type', 2); # 1=用户端登录,2=教师端登录
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password, $type);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


























    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }





    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }



    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }



    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
